/**
 * @author Kostya
 */

var TYPE_TEXT = 0;
var TYPE_IMAGE = 1;
var TYPE_AUDIO = 2;
var TYPE_TASK = 3;
var TYPE_EVENT = 4;
var TYPE_BMARK = 5;
var TYPE_FILE = 6;


var networkFlag = 0;
var iNetworkListener = function(){};
var iStatusBar = null;

var iStatusBarCaption = null;

var startNetwork = function(){
	if(++networkFlag==1){
		//Show panel
		if(iStatusBar)
			iStatusBar.showBusy('Requesting network...');
		if(iNetworkListener)
			iNetworkListener(true);
	}
}

var endNetwork = function(){
	if(--networkFlag==0){
		//Hide panel
		if(iStatusBar){
			iStatusBar.clearStatus({
				useDefaults: true
			});			
			if(iStatusBarCaption){
				iStatusBar.setText(iStatusBarCaption);
			}
		}
		if(iNetworkListener)
			iNetworkListener(false);
	}	
}

var showError = function(aMessage){
	alert(aMessage);
}

var translateError = function(aError){
	var err = "Unknown error";
	var object = {
		error: aError
	};
	if('DB_ERROR'==object.error)
		err = 'Database error, please try again';
	if('INVALID_END_DATE'==object.error)
		err = 'Invalid event end date provided. Please check entered data';
	if('INVALID_IMAGE'==object.error)
		err = 'Cannot upload file. Maybe file is too big';
	if('INVALID_LOGIN'==object.error)
		err = 'Invalid login name: Only alphanumeric and "_" characters allowed';
	if('INVALID_NAME'==object.error)
		err = 'Invalid name provided. This field is required';
	if('INVALID_START_DATE'==object.error)
		err = 'Invalid event start date. Please check entered data';
	if('INVALID_URL'==object.error)
		err = 'Invalid URL provided';
	if('INVALID_USER'==object.error)
		err = 'Invalid user name provided';
	if('INVALID_USER_PASS'==object.error)
		err = 'Invalid user name or password';
	if('LOGIN_TOO_SHORT'==object.error)
		err = 'Login name is too short, minimum length - 5 characters';
	if('NAME_TOO_SHORT'==object.error)
		err = 'Name is too short, minimum length - 5 characters';
	if('NO_PERMISSION'==object.error)
		err = 'You have no permission for this operation. Please check that someone granted you sufficient permissions';
	if('PASSWORD_TOO_SHORT'==object.error)
		err = 'Password too short, minimum length - 5 characters';
	if('START_DATE_LESS_END_DATE'==object.error)
		err = 'Event finish date is earlier than start date. Please provide correct dates';
	if('UPLOAD_FAILED'==object.error)
		err = 'File upload failed. Please upload another file';
	if('URL_TOO_LONG'==object.error)
		err = 'URL is too long. Maximum length is 255 characters';
	if('USER_EXISTS'==object.error)
		err = 'User with this name already exists. Please provide another one';
	// if(''==object.error)
	// 	err = '';
	return err;
}

function callAPI(server, api, params, okCallback, errorCallback, aObject) {
	var req = new XMLHttpRequest();
	req.onreadystatechange = function() { 
//	air.trace('state: '+req.readyState);	
        if (req.readyState == 4) {
			endNetwork();
//			air.trace('text: '+req.responseText);
            var lXML = req.responseXML;
			if(!lXML){
				//Report error
				showError('Can\'t establish connection with server, please verify connection settings');
				if(errorCallback)
					errorCallback();
				return;
			}
			if(lXML.getElementsByTagName("error").length>0){
				showError(translateError(
					lXML.getElementsByTagName("error")[0].firstChild.nodeValue));
				if(errorCallback)
					errorCallback();
			}else{
				if(okCallback)
					okCallback(lXML);
			}
        }
    };
	var lsURL = 'http://'+server+'/api/'+api;
	var liParamIndex = 0;
//	if(iToken)
//		params.token = iToken;
	for(var id in params){
		if(liParamIndex++==0)
			lsURL += '?';
		else
			lsURL += '&';
		lsURL += (id+'='+encodeURIComponent(params[id]));
	}
//	air.trace('URL: '+lsURL);
    req.open(aObject?'POST':'GET', lsURL, true);
	req.setRequestHeader("Cache-Control", "no-cache");
	startNetwork();
	if(aObject){
//		air.trace('Sending: '+aObject);
	    req.send(aObject);
	}else{
	    req.send(null);		
	}
	
}

function callURL(url, okCallback) {
	var req = new XMLHttpRequest();
	req.onreadystatechange = function() { 
        if (req.readyState == 4) {
			endNetwork();
//			air.trace('text: '+req.responseText);
			if(okCallback)
				okCallback(req.responseText);
        }
    };
//	air.trace('URL: '+url);
    req.open('GET', url, true);
//	req.setRequestHeader("Cache-Control", "no-cache");
	startNetwork();
    req.send(null);	
}

function sendForm(server, api, params, okCallback, errorCallback, aFile){
	var lsURL = 'http://'+server+'/api/'+api;
	var variables = new air.URLVariables();	
	for(var id in params){
		variables[id] = params[id]
	}
	var lCompleteHandler = function(e){
		endNetwork();
		if(okCallback)
			okCallback();
	};
	startNetwork();
	var lRequest = new air.URLRequest(lsURL);
	lRequest.method = air.URLRequestMethod.POST;
	lRequest.data = variables;
	if(aFile){
		aFile.addEventListener( air.Event.COMPLETE, lCompleteHandler);
		lRequest.contentType = 'multipart/form-data';
		aFile.upload(lRequest, 'file', false);
	}else{
		lRequest.contentType = 'application/x-www-form-urlencoded';		
		var lLoader = new air.URLLoader();
		lLoader.addEventListener( air.Event.COMPLETE, lCompleteHandler);
		lLoader.addEventListener(air.IOErrorEvent.IO_ERROR, function(){
			endNetwork();
			if(errorCallback)
				errorCallback();
		});
		lLoader.load(lRequest);
	}
}

var openNewWindow = function(aWinID, aWinSource, aWinType, aChrome, aTransparent){
	var win = null;
	if(win = Ext.air.NativeWindowManager.get(aWinID)) {
		win.instance.orderToFront();
		win.instance.activate();
		return false;
	} else {
		win = new Ext.air.NativeWindow({
			id: aWinID,
			file: aWinSource,
			chrome: aChrome?aChrome:'standard',
			type: aWinType?aWinType: 'normal',
			transparent: aTransparent
		});
	}
	return true;
}


var escapeHTML = function(s){
	if(!s)
		return '';
	var res = s.replace(/</g, '&lt;');
	res = res.replace(/>/g, '&gt;');
	res = res.replace(/\n/g, '<br/>');
	return res;
};

var generateRandomString = function(num){
	var chars = 'qwertyuiopasdfghjklzxcvbnm';
	var rstr = '';
	for (var i=0; i < num; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		rstr += chars.substring(rnum, rnum+1);
	}
	return rstr;
};
